package com.codebo.homiematchbackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.codebo.homiematchbackend.common.ErrorCode;
import com.codebo.homiematchbackend.config.CosClientConfig;
import com.codebo.homiematchbackend.exception.ThrowUtils;
import com.qcloud.cos.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FileManager
{
    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    public String uploadFile(MultipartFile multipartFile, String prefix)
    {
        //1.校验文件
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCode.PARAMS_ERROR);
        //限制文件大小
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 1024 * 1024 * 2, ErrorCode.PARAMS_ERROR, "文件大小超过2M");
        //限制文件格式
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        List<String> list = Arrays.asList("png", "jpg", "jpeg", "webp");
        ThrowUtils.throwIf(!list.contains(suffix), ErrorCode.PARAMS_ERROR, "推荐上传png,jpg,jpeg,webp格式的文件");


        //2.构建路径
        String filename = multipartFile.getOriginalFilename();
        //修改文件名为：time-uuid.xxx
        String uuid = RandomUtil.randomString(16);
        filename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(filename));
        String filePath = String.format("%s/%s", prefix, filename);
        File file = null;
        try
        {
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putObject(filePath, file);

            // 返回可访问的url
            return cosClientConfig.getHost() + filePath;
        } catch (Exception e)
        {
            log.error("文件上传出现异常, filepath = {}", filePath);
        } finally
        {
            // 删除临时文件
            boolean delete = false;
            if (file != null && file.exists())
            {
                delete = file.delete();
            }
            if (!delete)
            {
                log.error("文件上传失败, filepath = {}", filePath);
            }
        }
        return null;
    }
}
